package xuperchain

import (
	"fmt"
	"strings"

	"github.com/xuperchain/xuper-sdk-go/v2/account"
	"github.com/xuperchain/xuper-sdk-go/v2/xuper"
)

const path = "./key/"
const pwd = "xxxxxx"//密码
const contractAccount = "XC3239408961442245@xuper"
const nodeAddress = "14.215.183.139:37101"

func FileStorage(owner string, paperName string, abstract string, users string) (result string) {

	account, err := account.GetAccountFromFile(path, pwd)
	if err != nil {
		fmt.Printf("GetAccountFromFile err: %v\n", err)
		panic(err)
	}

	err = account.SetContractAccount(contractAccount)
	if err != nil {
		panic(err)
	}

	xchainClient, err := xuper.New(nodeAddress)
	if err != nil {
		panic(err)
	}

	contractName := "xc_filestorage8"

	// 添加文件
	argsAddFile := map[string]string{
		"_owner":   owner,
		"_name":    paperName,
		"_summary": abstract,
		"_hash":    "hash",
	}
	txAddFile, err := xchainClient.InvokeEVMContract(account, contractName, "addFile", argsAddFile)
	if err != nil {
		panic(err)
	}
	fmt.Printf("addFile success! TXID: %x\n", txAddFile.Tx.Txid)

	// 分割用户字符串并循环添加每个授权用户
	usernames := strings.Split(users, ";")
	for _, userPermission := range usernames {
		// 分割userPermission为username和permissionLevel
		parts := strings.Split(userPermission, ":")
		if len(parts) != 2 {
			fmt.Printf("Invalid user permission format for %s\n", userPermission)
			continue
		}
		username := parts[0]
		permissionLevel := parts[1]

		argsAddAuthorizedUser := map[string]string{
			"_name":            paperName,
			"_operator":        owner,
			"_username":        username,
			"_publicKey":       "publicKey",
			"_permissionLevel": permissionLevel,
		}

		fmt.Print(username)
		txAddAuthorizedUser, err := xchainClient.InvokeEVMContract(account, contractName, "addAuthorizedUser", argsAddAuthorizedUser)
		if err != nil {
			panic(err)
		}
		fmt.Printf("addAuthorizedUser success! TXID: %x\n", txAddAuthorizedUser.Tx.Txid)
	}

	return "success"
}
